#include "canmessage.h"
#include <QDebug>

CanMessage::CanMessage(QString USBCanString)
    : Identifier(0)
    , Data()
    , Valid(false)
{
    qDebug() << "Parsing " << USBCanString;
    ParseFromUSBCanString(USBCanString);
}

CanMessage::CanMessage(quint32 identifier, QVector<quint8> data)
    : Identifier(identifier)
    , Data(data)
    , Valid(true)
{
}

quint32 CanMessage::GetIdentifier()
{
    return Identifier;
}

unsigned int CanMessage::GetPGN()
{
    return (Identifier >> 8) & 0xffff;
}

unsigned int CanMessage::GetSA()
{
    return Identifier & 0xff;
}

QVector<quint8> CanMessage::GetData() const
{
    return Data;
}

int CanMessage::GetDataLength()
{
    return Data.size();
}

bool CanMessage::IsValid()
{
    return Valid;
}

QString CanMessage::GetAsSnifferSendString()
{
    QString retVal = QString("T%1%2").arg(Identifier, 8,16,QChar('0')).arg(Data.size(),1,16,QChar('0'));
    for(int i = 0; i < Data.size(); i++)
    {
        retVal.append(QString::number(Data[i], 16).rightJustified(2, '0'));
    }
    return retVal;
}

void CanMessage::ParseFromUSBCanString(QString USBString)
{
    if(USBString[0] == 'T')
    {
//        qDebug() << "We have an extended message";
        ParseExtendedMessage(USBString);
        Valid = true;
    }
}

void CanMessage::ParseExtendedMessage(QString USBString)
{
    bool trash;
    Identifier = USBString.mid(1,8).toInt(&trash, 16);
    for(int i = 10; i < USBString.size(); i+=2)
    {
        Data.append(USBString.mid(i,2).toInt(&trash, 16));
    }
}
